using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace Zero.Dialogue
{
    [Serializable]
    public class BubbleDialogueBehaviour : PlayableBehaviour
    {
        [Tooltip("气泡内容"), TextArea]
        public string body;
        [Tooltip("气泡持续时间(单位:秒 特殊值:-1=无限 0=默认)")]
        public float duration = -1f;
        [Tooltip("是否在片段播放完暂停")]
        public bool hasToPause = false;

        private bool _clipPlayed = false; // 片段是否播放过
        private bool _pauseScheduled = false; // 是否进行暂停
        private PlayableDirector _director; // 当前Timeline的播放器
        private BubbleCharacter _lastCharacter; // 最后说话的角色

        public override void OnPlayableCreate(Playable playable)
        {
            _director = playable.GetGraph().GetResolver() as PlayableDirector;
        }

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            if (!_clipPlayed
                && info.weight > 0f)
            {
                // 显示聊天气泡
                _lastCharacter = playerData as BubbleCharacter;
                if (_lastCharacter != null)
                {
                    if (duration == 0f) _lastCharacter.ShowBubbleCustom(body);
                    else _lastCharacter.ShowBubbleCustom(body, duration);
                }

                if (Application.isPlaying)
                {
                    if (hasToPause)
                    {
                        _pauseScheduled = true;
                    }
                }

                _clipPlayed = true;
            }
        }

        public override void OnBehaviourPause(Playable playable, FrameData info)
        {
            if (_pauseScheduled)
            {
                _pauseScheduled = false;
                // 暂停timeline
                _director.Pause();
            }
            else
            {
                // 关闭气泡窗口
                if (_lastCharacter != null && duration < 0f) _lastCharacter.HideBubble();
            }

            _clipPlayed = false;
        }
    }
}